
//
//  Date+string.swift
//  Medical
//
//  Created by WangLei on 15/8/6.
//  Copyright (c) 2015年 zhuxietong. All rights reserved.
//

import Foundation
extension TimeInterval
{
    public var hours:String{
        let time = Int64(self)
        let minutes = (time/60) % 60
        let hours = time / 3600
        
        if hours > 0 {
            return "[XX]小时 [YY]分钟".replaceVars(values: "\(hours)","\(minutes)")
//            return "\(hours)小时 \(minutes)分钟"
        }
        else
        {
            return "[XX]分钟".replaceVars(values: "\(minutes)")
//            return "\(minutes)分钟"
        }
    }
    
}

extension TimeInterval
{
    public var day_hour_minutes:String{
        
        let time = Int(self)
        
        let minutes = (time/60) % 60
        let hours = (time / 3600) % 24
        let days = (time / (3600*24))%24
        
        
        var return_str = "\(0)秒"
        var times = [String]()
        if days > 0
        {
            times.append("\(days) \("天".loc)")
        }
        
        if hours > 0
        {
            times.append("\(hours)\("小时".loc)")
        }
        if minutes > 0
        {
            times.append("\(minutes)\("分钟".loc)")
        }
        if times.count <= 0
        {
            times.append("\(time)\("秒".loc)")
        }
        return_str = times.joined(separator: "")

        if times.count < 0
        {
            
            return "\(0)\("秒".loc)"
        }
        
        return return_str
    }
    
    public var day_hour_minutes_seconds:(day:Int,hour:Int,minu:Int,sec:Int,isZore:Bool){
        
        let time = Int(self)
        
        let seconds = time % 60
        let minutes = (time/60) % 60
        let hours = (time / 3600) % 24
        let days = (time / (3600*24))%24
        
        
        var isZore = false
        
        var times = [String]()
        if days > 0
        {
            times.append("\(days)\("天".loc)")
        }
        
        if hours > 0
        {
            times.append("\(hours)\("小时".loc)")
        }
        if minutes > 0
        {
            times.append("\(minutes)\("分钟".loc)")
        }
        if times.count <= 0
        {
            times.append("\(time)\("秒".loc)")
        }
        
        if times.count < 0
        {
            
        }
        if (days == 0 && hours == 0 && minutes == 0 && seconds == 0){
            isZore = true
        }
        
        return (days,hours,minutes,seconds,isZore)
    }
    
    
    
}



public enum TimeCMResult : Int {
    
    case ealier
    case equal
    case later
}


extension ComparisonResult
{
    public var time:TimeCMResult{
        if self == .orderedAscending
        {
            return TimeCMResult.ealier
        }
        else if self == .orderedSame
        {
            return TimeCMResult.equal
        }
        else{
            return TimeCMResult.later
        }
    }
}


public enum TimeStamp精度 {
    case 秒
    case 毫秒
    public var x:Int64{
        get{
            switch self {
            case .秒:
                return 1
            default:
                return 1000
            }
        }
    }
}

extension Date
{
    
    public static var stamp精度:TimeStamp精度 = .毫秒
    
    public static func early(dates:[Date],date1_eary_date2:((_ date1:Date,_ date2:Date)->Bool)) -> Date {
        
        var early_date = dates[0]
        
        for one in dates{
            let is_early = date1_eary_date2(one,early_date)
            if is_early{
                early_date = one
            }
        }
        return early_date
    }
    
    public func timeSince(_ date:Date=Date()) -> (TimeCMResult,String) {
        
        let cmr = self.compare(date)
        
        let interval = self.timeIntervalSince(date)
        
        return (cmr.time,interval.day_hour_minutes)
        
    }
    public func timeSinceComponens(_ date:Date=Date()) -> (TimeCMResult,(day:Int,hour:Int,minu:Int,sec:Int)) {
        
        let cmr = self.compare(date)
        
        
        let interval = self.timeIntervalSince(date)
        
        var cm = cmr.time
        
        let info = interval.day_hour_minutes_seconds

        switch cmr.time {
        case .equal,.later:
            if (info.isZore){
                cm = .equal
            }
        default:
            break
        }
        
        return (cm,(info.day,info.hour,info.minu,info.sec))
    }
    
    
    public subscript(formatter:String) -> String {
        get {
            if formatter == "STAMP"
            {
                return self.time_stamp
            }
            else
            {
                let form = DateFormatter()
                form.dateFormat = formatter
                return form.string(from: self)
            }
        }
    }
    
    public var short_time:String
    {
        get {
            let str = self["YYYY-MM-dd HH:mm"]
            return str.replacingOccurrences(of: Date()["YYYY-"], with: "")
        }
    }
    public var short_cn_time:String
    {
        get {
            let str = self["YYYY年MM月dd日 HH:mm"]
            return str.replacingOccurrences(of: Date()["YYYY年"], with: "")
        }
    }
    
    public var date_string:String
    {
        get {
            return self["YYYY-MM-dd"]
        }
    }
    
    public var time_string:String
    {
        get {
            return self["HH:mm:ss"]
        }
    }
    
    
    public var cn_shot_time:String{
        get {
            return self["HH:mm"]
        }
    }
    
    public var cn_short_date:String
    {
        get {
            var str = self["MM月dd日".loc]
            str = str.replace(byReg: "月0", tag:"月 ")
            str = str.replace(byReg: "^0", tag: "")
            return str
        }
    }
    
    public var cn_short_date_time:String
    {
        get {
            return self["MM月dd日 HH:mm".loc]
        }
    }
    
    public var cn_full_date_time:String
    {
        get {
            return self["yyyy年MM月dd日 HH:mm".loc]
        }
    }
    
    
    public var server_date:String
    {
        get {
            return self["yyyy-MM-dd HH:mm:ss.SSS"]
        }
    }
    
    public var server_date1:String
    {
        get{
            return self["yyyyMMddHHmm"]
        }
    }
    
    public var time_stamp:String
    {
        get{
            return dateToTimeStamp(self)
        }
    }
}


extension Date{
    
    
    public var stamp:String{
        get{
            return dateToTimeStamp(self)
        }
    }
    
    static public func date(with stamp:String)->Date{
        return stampToTime(stamp)
    }
}
extension Date{
    public init?(str:String,fromat:String="yyyy-MM-dd") {
            let dfmatter = DateFormatter()
            dfmatter.dateFormat = fromat
            if let date = dfmatter.date(from: str)
            {
                
                self = date
                return
            }
        
        return nil
    }
}

public func timeStringToDate(_ time:String,format:String="yyyy-MM-dd HH:mm:ss.SSS") ->Date
{
    let dfmatter = DateFormatter()
    dfmatter.dateFormat = format
    if let date = dfmatter.date(from: time)
    {
        return date
    }
    return Date()
}

public func dateToTimeStamp(_ date:Date) ->String
{
    let fullTimeStr = date["yyyyMMddHHmmssSSS"]
    let fullTimeDate = timeStringToDate(fullTimeStr, format: "yyyyMMddHHmmssSSS")
    let dateStamp:TimeInterval = fullTimeDate.timeIntervalSince1970
    
    
    let dateSt:Int64 = Int64(dateStamp)*Date.stamp精度.x
    let stamp = String(dateSt)
    
    return stamp
}



public func timeStringTotimeStamp(_ stringTime:String)->String {
    
    let dfmatter = DateFormatter()
    dfmatter.dateFormat="yyyy年MM月dd日"
    let date = dfmatter.date(from: stringTime)
    
    let dateStamp:TimeInterval = date!.timeIntervalSince1970
    
    let dateSt:Int64 = Int64(dateStamp)
    return String(dateSt)
}



public func timeStampToTimeString(_ timeStamp:String)->String {
    
    let string = NSString(string: timeStamp)
    let timeSta:TimeInterval = string.doubleValue
    let dfmatter = DateFormatter()
    dfmatter.dateFormat="yyyy年MM月dd日"
    let date = Date(timeIntervalSince1970: timeSta)
    
    return dfmatter.string(from: date)
}
extension Date{
    public init?(time:String,format:String="yyyy-MM-dd") {
        self.init()
        do {
            let dfmatter = DateFormatter()
            dfmatter.dateFormat = time
        } catch {
            
        }
        let dfmatter = DateFormatter()
        dfmatter.dateFormat = time

        if let date = dfmatter.date(from: format)
        {
            self = date
        }
    }
    
    public init(stamp:String) {
        self.init()
        self = stampToTime(stamp)
    }
}



public func stampToTime(_ timeStamp:String)->Date {
    
    var stamp = timeStamp
    if timeStamp.jolength <= 10 {
        stamp = timeStamp + "000"
    }
    
    if let t = Double(stamp)
    {
        
        let date = Date(timeIntervalSince1970: t/1000.0)
        return date
    }
    
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    formatter.timeStyle = .short
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    if let date = formatter.date(from: stamp)
    {
        return date
    }
    
    
    return Date()
}

extension Date{
    
    
    public init?(utc:String,format:String = "yyyy-MM-dd'T'HH:mm:ssZ") {
        self.init()
        if let date = Date.utc(utc, format: format){
            self = date
        }else{
            return nil
        }
    }
    
    fileprivate static func utc(_ utc:String,format:String = "yyyy-MM-dd'T'HH:mm:ssZ") -> Date? {
//        demo utc = "2020-03-25T04:25:10Z"
        
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = format

        let date = dateFormatter.date(from: utc)
        dateFormatter.dateFormat = "yyyy-dd-MM HH:mm:ss"
        return date
    }
}

extension Date {

    /// 获取当前 秒级 时间戳 - 10位
    public var secondStampInt : Int64 {
        let timeInterval: TimeInterval = self.timeIntervalSince1970
        let timeStamp = Int64(timeInterval)
        return timeStamp
    }

    /// 获取当前 毫秒级 时间戳 - 13位
    public var milliStampInt : Int64 {
        let timeInterval: TimeInterval = self.timeIntervalSince1970
        let millisecond = CLongLong(round(timeInterval*1000))
        return millisecond
    }
    
    /// 获取当前 毫秒级 时间戳 - 13位
    public var milliStampStr : String {
        let timeInterval: TimeInterval = self.timeIntervalSince1970
        let millisecond = CLongLong(round(timeInterval*1000))
        return "\(millisecond)"
    }
}

extension Date{
    
    public func autoHidenYearOrDay() -> String{
        if self["yyyy-MM-dd"] == Date()["yyyy-MM-dd"]{
            return "今天".loc + " " + self["HH:mm"]
        }
        let result = self["yyyy年MM月dd日 HH:mm"]
        return result.replacingOccurrences(of: Date()["yyyy年"], with: "")
    }
    
    public func display(tip:String) ->String {
        let s1 = Date().secondStampInt - self.secondStampInt
        if s1 > (24 * 60 * 60){//大于1天
            let m1 = self["yyyy-MM"]
            let m2 = Date()["yyyy-MM"]
            if m1 == m2{
                return self["MM月dd日 HH:mm"]
            }else{
                return self["yyyy-MM-dd HH:mm"]
            }
        }else{
            if (s1 < 20 ){//小于秒
                return "刚刚"
            }
            if (s1 < 60 ){//小于秒
                return "\(s1)秒" + tip
            }
            else if (s1 < 60 * 60){
                let min = s1/60
//                let second = s1%60
                return "\(min)分钟 " + tip
            }else{
                let hour = s1/(60*60)
                let min = s1/60
//                let second = s1%60
                if hour < 2{
                    return "\(hour)小时\(min)分钟 " + tip
                }else{
                    return "\(hour)小时 " + tip
                }
            }
        }
    }
}
extension Date{
    public var messageTime:String{
        let calendar = Calendar.current
        let current = calendar.dateComponents([.year,.month,.day,.weekday,.hour,.minute,.second], from: self)
        
        let today = calendar.dateComponents([.year,.month,.day,.weekday,.hour,.minute,.second], from: Date())
        
        
        let format = DateFormatter()
        if today.year != current.year{
            format.dateFormat = "yyyy.MM.dd"
            return format.string(from: self)
            
        }else{
            if let todayD = today.day,let currentD = current.day{
                let dayDistance = todayD - currentD
                format.amSymbol = "上午"
                format.pmSymbol = "下午"

                switch dayDistance {
                case 0:
                    format.isLenient = true
                    format.dateFormat = "aaa hh:mm"
                    return format.string(from: self)
                case 1:
                    format.dateFormat = "HH:MM"
                    return "昨天 " + format.string(from: self)
                case 2,3,4,5,6,7:
                    format.dateFormat = "EEEE"
                    return format.string(from: self)
                default:
                    format.dateFormat = "yyyy.MM.dd"
                    return format.string(from: self)
                }
              
            }
            format.dateFormat = "yyyy.MM.dd"
            return format.string(from: self)
        }
        

        
    }
}
